from rest_framework import serializers
from .models import User


class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    stories_count = serializers.IntegerField(read_only=True)
    likes_received = serializers.IntegerField(read_only=True)
    join_date = serializers.DateTimeField(source='created_at', read_only=True)
    avatar_url = serializers.SerializerMethodField()
    
    class Meta:
        model = User
        fields = [
            'id', 'name', 'email', 'avatar', 'avatar_url', 'bio', 'role',
            'join_date', 'stories_count', 'likes_received', 'is_active'
        ]
        read_only_fields = ['id', 'role', 'join_date']
    
    def get_avatar_url(self, obj):
        """获取头像URL"""
        if obj.avatar:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.avatar.url)
            return obj.avatar.url
        return '/media/avatars/default.png'


class RegisterSerializer(serializers.Serializer):
    """注册序列化器"""
    name = serializers.CharField(max_length=50, min_length=2)
    email = serializers.EmailField()
    password = serializers.CharField(write_only=True, min_length=6)
    confirm_password = serializers.CharField(write_only=True)
    
    def validate_email(self, value):
        """验证邮箱是否已被注册"""
        if User.objects.filter(email=value).exists():
            raise serializers.ValidationError("该邮箱已被注册")
        return value
    
    def validate(self, data):
        """验证两次密码是否一致"""
        if data['password'] != data['confirm_password']:
            raise serializers.ValidationError("两次输入的密码不一致")
        return data
    
    def create(self, validated_data):
        """创建用户"""
        validated_data.pop('confirm_password')
        user = User.objects.create_user(**validated_data)
        return user


class LoginSerializer(serializers.Serializer):
    """登录序列化器"""
    email = serializers.EmailField()
    password = serializers.CharField(write_only=True)


class SendVerificationCodeSerializer(serializers.Serializer):
    """发送验证码序列化器"""
    email = serializers.EmailField()
    
    def validate_email(self, value):
        """验证邮箱是否已注册"""
        if not User.objects.filter(email=value).exists():
            raise serializers.ValidationError("该邮箱未注册")
        return value


class EmailCodeLoginSerializer(serializers.Serializer):
    """邮箱验证码登录序列化器"""
    email = serializers.EmailField()
    code = serializers.CharField(max_length=6, min_length=6)


class ResetPasswordSerializer(serializers.Serializer):
    """重置密码序列化器"""
    email = serializers.EmailField()
    code = serializers.CharField(max_length=6, min_length=6)
    new_password = serializers.CharField(required=True, min_length=6, write_only=True)
    confirm_password = serializers.CharField(required=True, write_only=True)
    
    def validate(self, data):
        """验证两次密码是否一致"""
        if data['new_password'] != data['confirm_password']:
            raise serializers.ValidationError("两次输入的密码不一致")
        return data


class ChangePasswordSerializer(serializers.Serializer):
    """修改密码序列化器"""
    old_password = serializers.CharField(required=True, write_only=True)
    new_password = serializers.CharField(required=True, min_length=6, write_only=True)
    confirm_password = serializers.CharField(required=True, write_only=True)
    
    def validate(self, data):
        """验证两次密码是否一致"""
        if data['new_password'] != data['confirm_password']:
            raise serializers.ValidationError("两次输入的密码不一致")
        return data


class UserUpdateSerializer(serializers.ModelSerializer):
    """用户信息更新序列化器"""
    class Meta:
        model = User
        fields = ['name', 'bio', 'avatar']
